package js.lee.jvli.db;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.sql.DataSource;

import js.lee.jvli.config.Configuration;
import js.lee.jvli.config.DataSourceNode;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DataSourceFactory {
    private static Logger          logger        = LoggerFactory.getLogger(DataSourceFactory.class);
    static Map<String, DataSource> dataSourceMap = new HashMap<String, DataSource>();

    private DataSourceFactory() {

    }

    public DataSourceFactory(List<DataSourceNode> dataSourceList) {
        for (DataSourceNode item : dataSourceList) {
            Properties config = new Properties();
            try {
                config.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(item.getConfig()));
                DataSource dataSource = DruidDataSourceFactory.createDataSource(config);
                dataSourceMap.put(item.getName(), dataSource);
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public DataSource getDataSource(String name) {
        if (dataSourceMap.containsKey(name)) {
            DataSource dataSource = dataSourceMap.get(name);
            return dataSource;
        }
        return null;
    }

    private static class SingletonHolder {
        private static final DataSourceFactory INSTANCE = new DataSourceFactory(Configuration.getInstance().getDataSourceList());
    }

    public static DataSourceFactory getInstance() {
        return SingletonHolder.INSTANCE;
    }
}
